package ai.mspbots.test.util;

import ai.mspbots.test.dto.ApiKeyDTO;
import ai.mspbots.test.entity.ApiKeyEntity;
import ai.mspbots.test.mapper.ApiKeyEntityMapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

@Component
public class OpenAIApiValidator {

    private final RestTemplate restTemplate;
    private final ApiKeyEntityMapper apiKeyEntityMapper;
    private static final String API_URL = "https://api.openai.com/v1/models";

    public OpenAIApiValidator(RestTemplate restTemplate, ApiKeyEntityMapper apiKeyEntityMapper) {
        this.restTemplate = restTemplate;
        this.apiKeyEntityMapper = apiKeyEntityMapper;
    }

    /**
     * 验证 API Key 是否有效
     *
     * @param apiKeyDTO 你的 OpenAI API Key
     * @return true 如果有效，false 如果无效或发生错误
     */
    public boolean isApiKeyValid(ApiKeyDTO apiKeyDTO) {
        // 1. 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        String apiKey = apiKeyDTO.getApiKey();
        headers.set("Authorization", "Bearer " + apiKey); // 关键：设置认证头

        HttpEntity<String> entity = new HttpEntity<>(headers);

        try {
            // 2. 发送 GET 请求
            ResponseEntity<String> response = restTemplate.exchange(
                    API_URL,
                    HttpMethod.GET,
                    entity,
                    String.class
            );

            // 3. 判断响应状态码
            if (response.getStatusCode() == HttpStatus.OK) {
                // 可以进一步解析 response.getBody() 来查看所有可用模型
                ObjectMapper mapper = new ObjectMapper();
                JsonNode root = mapper.readTree(response.getBody());
                ApiKeyEntity apiKeyEntity = ApiKeyEntity.covert(apiKeyDTO, root);
                apiKeyEntityMapper.insert(apiKeyEntity);
                return true;
            } else {
                System.out.println("❌ " + apiKey + " 验证失败，状态码: " + response.getStatusCode());
                return false;
            }
        } catch (HttpClientErrorException.Unauthorized e) {
            // 捕获 401 错误，明确表示 Key 无效
            System.out.println("❌ " + apiKey + " API Key 无效 (401 Unauthorized)。");
            return false;
        } catch (Exception e) {
            // 处理其他异常（如网络问题）
            System.out.println("❌ " + apiKey + " 验证过程中发生错误: " + e.getMessage());
            return false;
        }
    }
}